package service

import (
	"encoding/json"
	"gin/common"
	Mysql "gin/database"
	"gin/model"
	"gin/validate"
	"github.com/go-ego/gpy"
	"gorm.io/datatypes"
	"strings"
)

func CreateAction(data model.Action) (model.Action, error) {
	if data.Code == "" {
		data.Code = strings.Join(gpy.LazyConvert(data.Name, nil), "")
	}
	// 处理自定义标签的相似词查询
	if data.CustomTag != "" {
		data.TagSimilarWords = handleActionCustomTagSimilarWord(&data)
	}
	_, err := data.Insert()
	return data, err
}

func FindAction(Param common.SelectQueryParam) (resData model.Action, err error) {
	var logModel model.Action
	resData, err = logModel.Find(Param)
	return
}

func SelectAction(Param *common.SelectQueryParam) (total int64, resData []model.Action, err error) {
	var logModel model.Action

	total, resData, err = logModel.Select(Param)

	return
}

func UpdateAction(data validate.UpdateAction) (*model.Action, error) {
	res := new(model.Action)
	db := Mysql.DB

	res.Name = data.Name
	res.Code = data.Code
	res.Description = data.Description
	res.CustomTag = data.CustomTag
	res.PreviewImage = data.PreviewImage
	res.StoragePath = data.StoragePath

	// 处理自定义标签的相似词查询
	if data.CustomTag != "" {
		res.TagSimilarWords = handleActionCustomTagSimilarWord(res)
	}

	result := db.Model(&res).Where("id = ?", data.Id).Updates(&res)
	if result.Error != nil {
		return res, result.Error
	}
	result = db.Take(&res, data.Id)
	if result.Error != nil {
		return res, result.Error
	}
	return res, nil
}

func DeleteAction(param *common.Filter) {
	var logModel model.Action
	logModel.DeleteByFilter(param)
	return
}

func handleActionCustomTagSimilarWord(shot *model.Action) datatypes.JSON {
	customTagsArray := strings.Split(shot.CustomTag, ",")
	if len(customTagsArray) > 0 {
		customTagsSimilarWords := make([]string, 0)
		for _, word := range customTagsArray {
			validateSimilarWord := validate.QuerySimilarWordWithAnalysis{
				Word:    word,
				IsAsync: "no",
				Number:  10,
			}
			_, similarWords, err := QueryWordSimilarSimilarWords(&validateSimilarWord)
			if err != nil {
				continue
			}
			for _, sw := range similarWords {
				customTagsSimilarWords = append(customTagsSimilarWords, sw.Word)
			}
		}
		if len(customTagsSimilarWords) > 0 {
			shot.TagSimilarWords, _ = json.Marshal(customTagsSimilarWords)
		}
	}
	return shot.TagSimilarWords
}
